package com.hmdp.interceptor;

import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * ClassName: LoginInterceptort
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.22 1:04
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
    private StringRedisTemplate stringRedisTemplate;

    //在MvcConfig中注入，然后传参
    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
     */

    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /** 旧方式: 用session获取用户

         //1 获取session
         HttpSession session = request.getSession();
         //2 获取session中用户
         UserDTO user = (UserDTO) session.getAttribute("user");
         //3 判断用户是否存在
         if(user == null){
              //3.1 不存在，拦截
              //返回401状态码，代表未授权
              response.setStatus(401);
              return false;
              }

         //3.2 存在，保存用户到ThreadLocal
         UserHolder.saveUser(user);

         //3.2.1 放行
         return true;
         */

        /** 新方式: 用redis刷新token有效期
        但, 有些不登录也能访问的请求会被拦截, 故而分成两个Interceptor

         //获取token
        String authorization = request.getHeader("authorization");

        //用token获取在redis中的用户hash
        if(StrUtil.isBlank(authorization)){
            response.setStatus(401);
            return false;
        }
        Map userDTOMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + authorization);

        if(userDTOMap.isEmpty()){
            response.setStatus(401);
            return false;
        }
        //用户hash转为UserDTO对象
        UserDTO user = BeanUtil.fillBeanWithMap(userDTOMap, new UserDTO(), false);
        //保存用户到ThreadLocal
        UserHolder.saveUser(user);

        //刷新token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + authorization, LOGIN_USER_TTL, TimeUnit.MINUTES);

        //放行
        return true;
        */

        //判断是否需要拦截
        if(UserHolder.getUser() == null){
            response.setStatus(401);
            return false;
        }
        return true;
    }


    //后置拦截器
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
